package com.py.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.article.mapper.ApArticleConfigMapper;
import com.py.article.mapper.ApArticleContentMapper;
import com.py.article.mapper.ApArticleMapper;
import com.py.article.service.ApArticleService;
import com.py.common.constants.ArticleConstants;
import com.py.common.redis.CacheService;
import com.py.model.article.dtos.ArticleDto;
import com.py.model.article.dtos.ArticleHomeDto;
import com.py.model.article.dtos.HotArticleVo;
import com.py.model.article.pojos.ApArticle;
import com.py.model.article.pojos.ApArticleConfig;
import com.py.model.article.pojos.ApArticleContent;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.common.enums.AppHttpCodeEnum;
import com.py.model.search.vos.SearchArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/8 9:41
 * @Version 1.0
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Resource
    private ApArticleMapper articleMapper;
    @Resource
    private ApArticleConfigMapper configMapper;
    @Resource
    private ApArticleContentMapper contentMapper;
    @Autowired
    private ArticleDetailService articleDetailService;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private CacheService cacheService;

    private final static Integer DEFAULT_SIZE = 10;


    /**
     * 登录进去是首页 查找热点数据
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true 是首页  false 不是首页
     * @return
     */
    @Override
    public ResponseResult loadArticleListV2(ArticleHomeDto dto, Integer type, boolean firstPage) {
        if (firstPage) {
            //从缓存中获取数据
            String articleListStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (articleListStr != null) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        return loadArticle(dto, type);
    }

    @Override
    public ResponseResult loadArticle(ArticleHomeDto homeDto, Integer type) {
        paramCheck(homeDto);
        return ResponseResult.okResult(articleMapper.loadArticle(homeDto, type));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveArticle(ArticleDto dto) throws Exception {
        if (StringUtils.isEmpty(dto.getContent()) || StringUtils.isEmpty(dto.getTitle())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        apArticle.setPublishTime(new Date());

        if (dto.getId() == null) {
            save(apArticle);
            //保存文章配置
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsForward(true);
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsComment(true);
            configMapper.insert(config);

            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            contentMapper.insert(content);
        } else {
            updateById(apArticle);
            ApArticleContent content = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            content.setContent(dto.getContent());
            contentMapper.updateById(content);
        }

        //生成静态资源文件,保存到minio
        String url = articleDetailService.createStaticHtml(dto.getContent(), apArticle.getId());

        //发送消息 通知保存到ES
        try {
            SearchArticleVo searchArticleVo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle, searchArticleVo);
            searchArticleVo.setContent(dto.getContent());
            searchArticleVo.setStaticUrl(url);
            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
        } catch (BeansException e) {
            log.error("发送消息通知ES失败", e);
        }

        return ResponseResult.okResult(apArticle.getId());
    }


    /**
     * 参数校验
     * @param homeDto
     */
    private void paramCheck(ArticleHomeDto homeDto) {
        //基本判断
        if (homeDto.getMinBehotTime() == null) {
            homeDto.setMinBehotTime(new Date());
        }
        if (homeDto.getMaxBehotTime() == null) {
            homeDto.setMaxBehotTime(new Date());
        }
        if (homeDto.getSize() == null) {
            homeDto.setSize(DEFAULT_SIZE);
        }
        if (StringUtils.isEmpty(homeDto.getTag())) {
            homeDto.setTag("__all__");
        }
    }
}